/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useCallback } from "react";
import { Row, Col, Button, message } from "antd";
import { connect } from "dva";
import { isEmpty } from "lodash";
import { copy } from "@/utils/utils";

const BuildInMenuSelect = ({
  channel,
  onDelete,
  tcjsOpened,
  buildInMenu,
  onShowClick,
  currentMiniAppPlatform, // 当前用户绑定在新零售的小程序
  systemMenuURL,
}) => {
  const { platformName: currentMiniAppName } = currentMiniAppPlatform;

  const [showError, setShowError] = useState(false);

  const onClick = useCallback(
    () => {
      if (channel === "miniprogram" && isEmpty(currentMiniAppPlatform)) {
        setShowError(true);
        return;
      }
      onShowClick && onShowClick();
    },
    [channel, currentMiniAppPlatform, onShowClick]
  );

  const onRemove = () => {
    onDelete && onDelete();
  };

  const onCopy = useCallback(
    () => {
      systemMenuURL &&
        copy(systemMenuURL, copied => {
          if (copied) {
            message.success("复制成功！");
          } else {
            message.warning("复制失败");
          }
        });
    },
    [systemMenuURL]
  );

  if (channel === "miniprogram" && isEmpty(currentMiniAppPlatform) && showError) {
    return (
      <Row>
        <Col style={{ color: "red" }}>
          未定制小程序或定制后未关联，请联系客服定制或
          <a href="https://www.kuaidihelp.com/index/mail" target="_blank" rel="noreferrer">
            点击定制
          </a>
        </Col>
      </Row>
    );
  }

  return (
    <Row type="flex" gutter={[20, 0]}>
      <Col>
        <a onClick={onClick}>选择系统内置链接</a>
      </Col>
      <Col>
        {buildInMenu.name && (
          <Row type="flex" gutter={[10, 0]}>
            {tcjsOpened ? (
              <>
                <Col>已选择系统链接:</Col>
                <Col>{buildInMenu.name}</Col>
                {currentMiniAppName &&
                  channel === "miniprogram" && (
                    <>
                      <Col>跳转小程序:</Col>
                      <Col>{currentMiniAppName}</Col>
                    </>
                  )}
              </>
            ) : (
              <Col style={{ color: "red" }}>
                同城急送功能需要联系客服开通后添加，请点击右上角“联系客服”，咨询开通事宜
              </Col>
            )}
            <Col>
              <Button size="small" type="danger" ghost onClick={onRemove}>
                删除
              </Button>
            </Col>
            {systemMenuURL && tcjsOpened && (
              <Col>
                <Button size="small" type="primary" ghost onClick={onCopy}>
                  复制系统连接
                </Button>
              </Col>
            )}
          </Row>
        )}
      </Col>
    </Row>
  );
};

export default connect(({ wxSettings }) => ({
  miniProgramMenuMap: wxSettings.miniProgramMenuMap,
  officialMenuMap: wxSettings.officialMenuMap,
  systemMenuURL: wxSettings.systemMenuURL,
}))(BuildInMenuSelect);
